/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.common.action;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Attachment;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Mail;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.AttachmentService;
import etcore.webapp.grouptalk.common.service.CommentService;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MailService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.user.object.Favourite;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.FavouriteService;
import etcore.webapp.grouptalk.user.service.MemberService;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.MailSender;
import etcore.webapp.grouptalk.util.StringDisplay;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of showing message
 * detail,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class MessageDetailAction extends AbstractAction {

	private static final long serialVersionUID = -2803897256660960817L;
	// validate result
	public static final int ERROR = 0;
	public static final int ACCESSIBLE = 1;
	public static final int ADMIN = 2;
	public static final int NOT_LOGGED = 3;

	// parameters constants
	public static final String CMD_ADD_COMMENT = "addGcomment";
	public static final String CMD_ADD_FAVOURITE = "addFavourite";
	public static final String CMD_NAME = "cmd";
	public static final String CMD_ADD_ATTACHMENT = "addAtt";
	public static final String CMD_EDIT_ATTACHMENT = "editAtt";
	public static final String CMD_DEL_COMMENT = "delGcomment";
	public static final String CMD_SHARE = "share";

	public static final String REPLYABLE = "replyable";
	public static final String RELATED = "related";
	public static final String DELETE_COMMENT_ALLOWED = "delete";
	public static final String RANKV = "rankv";
	public static final String SOURCE_RANKV = "sourceRankv";
	public static final String CMD_SORT_ATTACHMENTS = "sortAttachments";
	public static final String CMD_ASSIGN_COMMENTS = "assignComments";
	public static final String ATTACHMENT_SIZE = "attachmentSize";

	// forward pages

	public static final String ERROR_PAGE = "/error.jsp";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			int right = 0;
			boolean isAdmin = (Boolean) request
					.getAttribute(PageConstants.ISADMIN);
			String gmid = request.getParameter(PageConstants.ID);
			Message msg = null;
			Topic topic = null;
			Group group = null;
			MessageService msgService = new MessageService();
			TopicService topicService = new TopicService();
			GroupService groupService = new GroupService();
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			boolean included = true;

			if (gmid != null) {
				msg = msgService.findById(new Integer(gmid));
				if (msg != null) {
					topic = topicService.findById(new Integer(msg.getTid()));
					if (topic != null) {
						group = groupService.findById(new Integer(topic
								.getGid()));
						if (group != null) {

							boolean groupMember = false;
							if (user != null && user.getIsLock() != 1) {
								MemberService memberService = new MemberService();
								Member member = memberService
										.findByUsernameAndGid(
												user.getUserName(),
												new Integer(group.getId()));

								if (member != null && member.getLocked() == 0)
									groupMember = true;

							}

							if ((group.getFunc() == 0
									&& group.getOpen().intValue() >= 1 && msg
									.getFlag() >= 0) || isAdmin||groupMember) {
								request.setAttribute(REPLYABLE, true);
								@SuppressWarnings("rawtypes")
								List related = msgService.findMsgsByGid(
										group.getId(), 0, 10);

								request.setAttribute(RELATED, related);
								right = 1;
							}

							if (user != null) {
								FavouriteService favouriteService = new FavouriteService();
								if (!favouriteService.isAdded(
										user.getUserName(), new Integer(gmid)))
									included = false;
							}
						}
					}
				}
			}
			if (right == 1) {
				String encryptedUrlStr = Config
						.getProperty(Config.MSG_ENCRYPTEDURL);

				if (Messages.TRUE.equals(encryptedUrlStr))
					request.setAttribute(Messages.ENCRYPTED, true);
				else
					request.setAttribute(Messages.ENCRYPTED, false);

				request.setAttribute(PageConstants.MESSAGEDETAIL, msg);
				request.setAttribute(PageConstants.GROUP, group);
				request.setAttribute(PageConstants.TOPIC, topic);
				request.setAttribute("included", included);

			}
			if (isAdmin)
				return ADMIN;
			if (right == 1)

				return ACCESSIBLE;
			if (user == null)
				return NOT_LOGGED;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ACCESSIBLE == validationResult || ADMIN == validationResult)
			return PageConstants.PAGE_PATH_MESSAGEDETAIL;
		else if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}

		return ERROR_PAGE;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {

		if (validationResult == ADMIN || validationResult == ACCESSIBLE) {

			sortAttachments(request);
			editAttachment(request);
			deleteAttachment(request);
			try {
				addAttachment(request);
			} catch (Exception e) {
				e.printStackTrace();

			}
			addAttachmentUsingUrl(request);
			if (validationResult == ADMIN) {

				assignComments(request);
			}
			// click count ++
			visit(request);

			// add favourite

			addFavourite(request);

			// add comment if requested
			addComment(request, validationResult);

			delGcomment(request);

			getGroups(request);

			getTopics(request);

			// if requested
			getReminderDate(request);

			// get comments
			getComments(request);

			// get attachments
			getAttachments(request);

			if (validationResult == ADMIN) {
				share(request);
				getSystemAdmins(request);
			}
		}
	}

	public void addAttachment(HttpServletRequest request) throws IOException {
		String cmd = request.getParameter(CMD_NAME);
		if (CMD_ADD_ATTACHMENT.equals(cmd)) {

			HttpSession session = request.getSession(true);
			String lang = (String) session.getAttribute("lang");
			Message message = (Message) request
					.getAttribute(PageConstants.MESSAGEDETAIL);
			Group group = (Group) request.getAttribute(PageConstants.GROUP);
			Topic topic = (Topic) request.getAttribute(PageConstants.TOPIC);
			boolean included = (Boolean) request.getAttribute("included");

			try {
				String gmid = null;

				User user = (User) session.getAttribute("session_user");

				Attachment attachment = new Attachment();
				AttachmentService attachmentSevice = new AttachmentService();
				String webInfPath = this.getServletConfig().getServletContext()
						.getRealPath("WEB-INF");
				String rootWebPath = webInfPath.substring(0,
						webInfPath.indexOf("WEB-INF"));
				String uploadPath = rootWebPath + PageConstants.ATTACHMENT_PATH;
				String tempPath = rootWebPath + PageConstants.UPLOAD_TEMP_PATH;

				String attached = null;
				String name = null;

				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload fileUpload = new DiskFileUpload();

				fileUpload.setSizeMax(10 * 1024 * 1024);

				fileUpload.setSizeThreshold(4096);

				fileUpload.setRepositoryPath(tempPath);

				@SuppressWarnings("rawtypes")
				List items = fileUpload.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator itemIterator = items.iterator();

				while (itemIterator.hasNext()) {
					FileItem fi2 = (FileItem) itemIterator.next();

					if (fi2.isFormField()) {
						if (fi2.getFieldName().equals("name")) {
							name = fi2.getString(PageConstants.ENCODING_UTF8);

						} else if (fi2.getFieldName().equals("id")) {
							gmid = fi2.getString(PageConstants.ENCODING_UTF8);

						}

					}
					if (!fi2.isFormField()) {
						int fileError = 0;
						String fileName = fi2.getName();
						if (fileName != null)
							fileName = fileName
									.substring(fileName
											.lastIndexOf(Symbols.DOUBLE_BACK_SLASH) + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);

							fileName = new java.sql.Timestamp(
									System.currentTimeMillis()).toString()
									.substring(0, 13)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(14, 16)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(17, 19)
									+ suffixName;
							if (name == null || "".equals(name.trim())) {
								name = fileName;
							}
							attached = PageConstants.ATTACHMENT_PATH + fileName;

							File savedFile = new File(uploadPath, fileName); //

							fi2.write(savedFile);//

						}

					}
				}
				attachment.setGmid(new Integer(gmid));
				attachment.setName(name);
				attachment.setUserName(user.getUserName());
				attachment.setAttached(attached);
				attachment.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));

				attachmentSevice.save(attachment);

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
			} catch (Exception e) {

				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_UPLOAD_ERROR);
				} else {
					msg = Messages.getLabel(Messages.MSG_UPLOAD_ERROR);
				}
				request.setAttribute(Messages.MSG, msg);

				e.printStackTrace();
				return;
			}

			request.setAttribute(PageConstants.MESSAGEDETAIL, message);

			request.setAttribute(PageConstants.GROUP, group);
			request.setAttribute(PageConstants.TOPIC, topic);
			request.setAttribute("included", included);
		}
	}

	private void editAttachment(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (CMD_EDIT_ATTACHMENT.equals(cmd)) {
			String aid = request.getParameter("aid");

			String name = request.getParameter(PageConstants.NAME);
			if (aid != null) {
				AttachmentService attachmentService = new AttachmentService();
				Attachment targetAtt = attachmentService.findById(new Integer(
						aid));
				if (targetAtt != null) {
					targetAtt.setName(name);
					attachmentService.merge(targetAtt);
				}
			}
			HttpSession session = request.getSession(true);

			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(PageConstants.MSG, msg);

		}
	}

	private void getAttachments(HttpServletRequest request) {
		Message message = (Message) request
				.getAttribute(PageConstants.MESSAGEDETAIL);
		AttachmentService attachmentService = new AttachmentService();
		List<Attachment> attachments = attachmentService.findByProperty(
				PageConstants.GMID, message.getId());
		request.setAttribute(ATTACHMENT_SIZE, attachments.size());
		request.setAttribute("attachments", attachments);

	}

	private void getSystemAdmins(HttpServletRequest request) {
		MemberService memberService = new MemberService();
		String admins = memberService.getSystemAdmins(0, 50);

		request.setAttribute("admins", admins);

	}

	private void sortAttachments(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (CMD_SORT_ATTACHMENTS.equals(cmd)) {
			AttachmentService attachmentService = new AttachmentService();

			Message message = (Message) request
					.getAttribute(PageConstants.MESSAGEDETAIL);
			List<Attachment> attachments = attachmentService.findByProperty(
					PageConstants.GMID, message.getId());

			String sourceRankv = request.getParameter(SOURCE_RANKV);
			String rankv = request.getParameter(RANKV);
			if (sourceRankv != null && rankv != null) {
				int sourceRankvInt = Integer.parseInt(sourceRankv);
				int rankvInt = Integer.parseInt(rankv);
				if (sourceRankvInt <= attachments.size()
						&& rankvInt <= attachments.size()) {
					for (int tmpCount = 0; tmpCount < attachments.size(); tmpCount++) {
						Attachment tmpAttachment = (Attachment) attachments
								.get(tmpCount);
						if (tmpCount != tmpAttachment.getRankv() - 1) {
							tmpAttachment.setRankv(tmpCount + 1);
							attachmentService.merge(tmpAttachment);
						}
					}
					if (sourceRankvInt < rankvInt) {
						for (int tmpCount = sourceRankvInt + 1; tmpCount <= rankvInt; tmpCount++) {
							Attachment tmpAttachment = (Attachment) attachments
									.get(tmpCount - 1);
							tmpAttachment
									.setRankv(tmpAttachment.getRankv() - 1);
							attachmentService.merge(tmpAttachment);
						}
					} else if (sourceRankvInt > rankvInt) {
						for (int tmpCount = rankvInt; tmpCount <= sourceRankvInt - 1; tmpCount++) {
							Attachment tmpAttachment = (Attachment) attachments
									.get(tmpCount - 1);
							tmpAttachment
									.setRankv(tmpAttachment.getRankv() + 1);
							attachmentService.merge(tmpAttachment);
						}
					}
					Attachment sourceTopic = (Attachment) attachments
							.get(sourceRankvInt - 1);

					if (sourceTopic != null) {
						sourceTopic.setRankv(rankvInt);

						attachmentService.merge(sourceTopic);

					}

				}
			}
		}

	}

	private void deleteAttachment(HttpServletRequest request) {
		String aid = request.getParameter("aid");
		String op = request.getParameter("op");
		String gmid = request.getParameter("id");
		// delete attachment
		if (aid != null && op != null && op.equals("delAtt")) {
			AttachmentService attachmentService = new AttachmentService();
			Attachment delAtt = attachmentService.findById(new Integer(aid));
			if (delAtt != null && delAtt.getGmid() == Integer.parseInt(gmid)) {
				attachmentService.deleteSingle(delAtt);
			}
		}
	}

	private void share(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
		String cmd = request.getParameter(CMD_NAME);
		if (user != null && CMD_SHARE.equals(cmd)) {
			String[] targetUserNames = null;
			StringBuffer emailBuffer = new StringBuffer();
			String userNames = request.getParameter("userNames");
			String userEmails = request.getParameter("userEmails");
			UserService userService = new UserService();
			if (userNames != null)
				targetUserNames = userNames.split(",|;");
			if (targetUserNames != null) {
				for (String targetUserName : targetUserNames) {

					User targetUser = userService
							.findByUserName(targetUserName);
					if (targetUser != null) {
						emailBuffer.append(targetUser.getEmail());
						emailBuffer.append(Symbols.COMMA);
					}
				}
			}
			if (userEmails != null)
				emailBuffer.append(userEmails);

			Message message = (Message) request
					.getAttribute(PageConstants.MESSAGEDETAIL);
			MailService mailService = new MailService();
			StringBuffer stringBuffer = new StringBuffer();

			stringBuffer.append("<p align=center><b>");
			stringBuffer.append(message.getName());
			stringBuffer.append("</b></p>");

			stringBuffer.append("<p align=left>From <b>");
			stringBuffer.append(user.getUserName());
			stringBuffer.append("</b></p>");

			stringBuffer.append(request.getRequestURL());

			stringBuffer.append("?id=" + message.getId());
			stringBuffer.append("<br/>");
			stringBuffer.append(message.getContent());
			Mail mail = new Mail();
			mail.setName(message.getName());
			mail.setContent(stringBuffer.toString());
			mail.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			mail.setToUsers(emailBuffer.toString());
			mail.setUserName(user.getUserName());
			mail.setFromUser(user.getUserName());
			mailService.save(mail);

			MailSender.sendEmail(mail);
		}
	}

	private void addFavourite(HttpServletRequest request) {
		String cmd = request.getParameter(CMD_NAME);
		if (CMD_ADD_FAVOURITE.equals(cmd)) {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			if (user != null) {
				String gmid = request.getParameter(PageConstants.ID);
				FavouriteService favouriteService = new FavouriteService();
				if (!favouriteService.isAdded(user.getUserName(), new Integer(
						gmid))) {
					Favourite favourite = new Favourite();
					favourite.setUserName(user.getUserName());
					favourite.setMid(new Integer(gmid));
					favourite.setAddTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
					favouriteService.save(favourite);
					String msg = null;
					String lang = (String) session.getAttribute("lang");
					if (lang != null && lang.equals(Messages.LANG_EN)) {
						msg = Messages.getELabel(Messages.MSG_SUCCESS);
					} else {
						msg = Messages.getLabel(Messages.MSG_SUCCESS);
					}
					request.setAttribute(Messages.MSG, msg);
					request.setAttribute("included", true);
				}
			}
		}

	}

	private void delGcomment(HttpServletRequest request) {
		String cmd = request.getParameter(CMD_NAME);
		if (CMD_DEL_COMMENT.equals(cmd)) {

			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute("session_user");
			boolean isAdmin = (Boolean) request.getAttribute("isAdmin");
			String id = request.getParameter("commentId");
			int flag = 0;
			Comment comment = null;
			CommentService commentService = new CommentService();
			if (id != null && user != null) {
				comment = commentService.findById(new Integer(id));
				if (comment != null
						&& comment.getUserName().equals(user.getUserName()))
					flag = 1;

				if (flag == 0 && isAdmin) {
					flag = 1;
				}

				if (flag == 1) {
					commentService.deleteSingle(comment);

				}
			}

			if (flag == 1) {
				String msg = null;
				String lang = (String) session.getAttribute("lang");
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);

			}
		}

	}

	private void addAttachmentUsingUrl(HttpServletRequest request) {
		// add attachment using url
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(Messages.SESSION_USER);
		String urlLink = request.getParameter("urlLink");
		String gmid = request.getParameter(PageConstants.ID);
		if ("true".equals(urlLink)) {
			AttachmentService attachmentService = new AttachmentService();
			String url_ = request.getParameter("url");
			String att_name = request.getParameter("att_name");
			if (url_ != null && !"".equals(url_)) {
				Attachment att_ = new Attachment();
				att_.setGmid(new Integer(gmid));
				att_.setName("" + att_name);
				att_.setUserName(user.getUserName());
				att_.setAttached(url_);
				att_.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				attachmentService.save(att_);
			}
		}
	}

	private void addComment(HttpServletRequest request, int validationResult) {
		Boolean replyable = (Boolean) request.getAttribute(REPLYABLE);
		if (replyable != null && replyable) {
			String cmd = request.getParameter(CMD_NAME);
			if (CMD_ADD_COMMENT.equals(cmd)) {
				HttpSession session = request.getSession(true);
				User user = (User) session.getAttribute(Messages.SESSION_USER);
				if (user == null)
					return;
				if (user.getIsLock() == 1) {
					String msg = null;
					String lang = (String) session.getAttribute("lang");
					if (lang != null && lang.equals(Messages.LANG_EN)) {
						msg = Messages.getELabel(Messages.ACTIVATION_FIRST);
					} else {
						msg = Messages.getLabel(Messages.ACTIVATION_FIRST);
					}
					request.setAttribute(Messages.MSG, msg);
					return;
				}

				Comment gc = new Comment();

				String lang = (String) session.getAttribute(Messages.LANG);
				CommentService commentService = new CommentService();
				Message message = (Message) request
						.getAttribute(PageConstants.MESSAGEDETAIL);
				String content = request.getParameter("content");
				String flag = request.getParameter(PageConstants.FLAG);
				if (flag != null)
					gc.setFlag(Integer.parseInt(flag));
				gc.setGmid(new Integer(message.getId()));

				gc.setContent(StringDisplay.secureOutput(content));
				gc.setUserName(user.getUserName());
				gc.setTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				commentService.save(gc);
				String msg = null;
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
			}
		}
	}

	private void getComments(HttpServletRequest request) {
		// get comments
		int intpageid = 1;
		CommentService commentService = new CommentService();
		UserService userService = new UserService();
		Message message = (Message) request
				.getAttribute(PageConstants.MESSAGEDETAIL);
		int unit = 10;
		long all;
		int begin, pagenums;
		String pageid = request.getParameter(PageConstants.PAGEID);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		all = commentService.findSizeByProperty(PageConstants.GMID,
				message.getId());
		pagenums = (int) ((all + unit - 1) / unit);
		begin = unit * (intpageid - 1);
		List<Comment> comments = commentService.findByProperty(
				PageConstants.GMID, message.getId(), begin, unit);
		if (all > 0 && comments != null)
			for (Comment comment : comments) {
				User toUser = userService.findByUserName(comment.getUserName());
				if (toUser != null)
					request.setAttribute(comment.getUserName()
							+ PageConstants.AVATAR_POSTFIX, toUser.getAvatar());
			}
		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;
		request.setAttribute("hiddenCommentsSize", commentService
				.findHiddenSizeByProperty(PageConstants.GMID, message.getId()));
		request.setAttribute(PageConstants.START_PID, startpid);
		request.setAttribute(PageConstants.END_PID, endpid);
		request.setAttribute(PageConstants.INTPAGEID, intpageid);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute("comments", comments);

	}

	private void assignComments(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (CMD_ASSIGN_COMMENTS.equals(cmd)) {
			Message message = (Message) request
					.getAttribute(PageConstants.MESSAGEDETAIL);
			CommentService commentService = new CommentService();
			UserService userService = new UserService();
			MemberService memberService = new MemberService();
			int MAX_SECONDS_LATER = 24 * 60 * 60;
			long sysAdminCount = memberService.getSysAdminNum();
			String fromUser = null, lastTime = null;
			int dateGap = 0;
			List<Comment> comments = commentService.findHiddenByProperty(
					PageConstants.GMID, message.getId());
			if (comments != null)
				for (Comment comment : comments) {
					int randomUesrIndex = (int) (Math.random() * sysAdminCount);
					fromUser = memberService
							.getSystemAdmins(randomUesrIndex, 1);

					dateGap = DateUtil.getQuot(DateUtil.getDate(),
							message.getAddtime()) + 1;
					int seconds = (int) (Math.random() * MAX_SECONDS_LATER * dateGap);
					lastTime = DateUtil.getLaterTime(
							(String) message.getAddtime(), seconds);

					comment.setUserName(fromUser);
					comment.setTime(lastTime);
					comment.setFlag(0);
					commentService.merge(comment);

					User user = userService.findByUserName(fromUser);
					if (user != null) {
						user.setLastTime(lastTime);
						user.setLoginNum(user.getLoginNum() + 1);
						userService.merge(user);

					}
				}
		}
	}

	private void getGroups(HttpServletRequest request) {
		List<Group> groupList = null;
		int groupNum = 50;
		String groupNumStr = request.getParameter(PageConstants.GROUPNUM);
		if (groupNumStr != null && !Symbols.BLANK.equals(groupNumStr))
			groupNum = Integer.parseInt(groupNumStr);
		GroupService groupService = new GroupService();
		Group group = (Group) request.getAttribute(PageConstants.GROUP);
		if (group.getOpen() == 1) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_NEWSVIEW);
		} else if (group.getOpen() == 2) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_COMMUNITYVIEW);
		} else if (group.getOpen() == 3) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_BOOKMARKSVIEW);
		} else {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_GROUPDETAIL);
		}

		DirectoryService directoryService = new DirectoryService();
		List<Directory> directories = directoryService.findByGid(group.getId());
		if (directories != null && directories.size() > 0)
			request.setAttribute("currentDirectory", directories.get(0));

		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (Messages.LANG_EN.equals(lang)) {

			groupList = groupService.findBy2Properties(PageConstants.OPEN,
					group.getOpen(), Messages.LANG_EN, new Integer(1), 0,
					groupNum);
		} else {
			groupList = groupService.findBy2Properties(PageConstants.OPEN,
					group.getOpen(), Messages.LANG_LOCAL, new Integer(1), 0,
					groupNum);
		}
		request.setAttribute(PageConstants.GROUPS, groupList);
	}

	private void getTopics(HttpServletRequest request) {
		TopicService topicService = new TopicService();
		Group group = (Group) request.getAttribute(PageConstants.GROUP);
		List<Topic> topics = topicService.findByProperty(PageConstants.GID,
				new Integer(group.getId()));
		request.setAttribute(PageConstants.TOPICS, topics);
	}

	private void getReminderDate(HttpServletRequest request) {
		Group group = (Group) request.getAttribute(PageConstants.GROUP);
		if (group.getOpen() == 4) {

			Message message = (Message) request
					.getAttribute(PageConstants.MESSAGEDETAIL);
			StringBuffer reminderDateBuffer = StringDisplay
					.getReminderDateStringBuffer(message.getSource(),
							message.getStime());

			request.setAttribute("reminderDate", reminderDateBuffer.toString());

		}
	}

	private void visit(HttpServletRequest request) {
		Message message = (Message) request.getAttribute("messageDetail");
		if (message == null)
			return;
		// clicked ++
		message.setNum(message.getNum() + 1);
		MessageService msgService = new MessageService();
		msgService.merge(message);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
